package com.zhu.library_management_system.controller;

import com.zhu.library_management_system.jwt.TokenService;
import com.zhu.library_management_system.pojo.BookBorrowing;
import com.zhu.library_management_system.responseMessage.ResponseMessage;
import com.zhu.library_management_system.service.BookBorrowingService;
import com.zhu.library_management_system.service.BookService;
import com.zhu.library_management_system.service.UserService;
import com.zhu.library_management_system.util.RoleVerify;
import com.zhu.library_management_system.util.VerifyLoginUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.catalina.valves.ErrorReportValve;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.xml.ws.Response;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

@RestController
@RequestMapping("/user/bookBorrowing")
@Api(tags = "借阅管理接口")
public class BookBorrowingController {
    @Autowired
    private BookBorrowingService bookBorrowingService;
    @Autowired
    private BookService bookService;
    @Autowired
    private UserService userService;

    @GetMapping("/findBookBorrowingAll")
    @ApiOperation("获取所有借阅记录")
    public ResponseMessage<List<BookBorrowing>> findBookBorrowingAll(@RequestHeader("Authorization") String token){
        Integer loginId = VerifyLoginUtil.verifyLogin(token);
        if (loginId == null || VerifyLoginUtil.isTokenValid(token)){
           return ResponseMessage.success(401, "Token无效或已过期", null);
        }

        if (RoleVerify.verifyRole(userService.getRole(loginId).getRole()).equals(null) || !RoleVerify.verifyRole(userService.getRole(loginId).getRole()).equals(0)){
            return ResponseMessage.success(403, "抱歉，你无权进行此操作！", null);
        }

        Iterable<BookBorrowing> bookBorrowing = bookBorrowingService.findBookBorrowingAll();
        List<BookBorrowing> bookBorrowingListList = StreamSupport.stream(bookBorrowing.spliterator(), false)
                .collect(Collectors.toList());
        return ResponseMessage.success(bookBorrowingListList);
    }

    @GetMapping("/findBookBorrowingById/{id}")
    @ApiOperation("根据借阅记录ID获取借阅记录信息")
    public ResponseMessage<BookBorrowing> findBookBorrowingById(@RequestHeader("Authorization") String token, @PathVariable Integer id){
        Integer loginId = VerifyLoginUtil.verifyLogin(token);
        if (loginId == null || VerifyLoginUtil.isTokenValid(token)){
           return ResponseMessage.success(401, "Token无效或已过期", null);
        }

        if (RoleVerify.verifyRole(userService.getRole(loginId).getRole()).equals(null) || !RoleVerify.verifyRole(userService.getRole(loginId).getRole()).equals(0)){
            return ResponseMessage.success(403, "抱歉，你无权进行此操作！", null);
        }

        try {
            BookBorrowing bookBorrowing = bookBorrowingService.findBookBorrowingById(id);
            return ResponseMessage.success(bookBorrowing);
        }catch (RuntimeException e){
            return ResponseMessage.success(404, e.getMessage(), null);
        }
    }

    @PostMapping("/borrowBook")
    @ApiOperation("借阅书籍")
    public ResponseMessage<BookBorrowing> borrowBook(@RequestHeader("Authorization") String token, @RequestBody BookBorrowing bookBorrowing) {
        Integer userId = VerifyLoginUtil.verifyLogin(token);
        if (userId == null || VerifyLoginUtil.isTokenValid(token)){
            return ResponseMessage.success(401, "Token无效或已过期", null);
        }
        bookBorrowing.setUserId(userId);
        if (userService.SelectUser(bookBorrowing.getUserId()) == null){
            return ResponseMessage.success(404, "用户不存在！", null);
        }

        if (bookBorrowingService.countUserBorrowing(bookBorrowing.getUserId()) == null){
            if ((RoleVerify.verifyRole(userService.getRole(userId).getRole()).equals(1) && bookBorrowing.getBookCount()>5) || (RoleVerify.verifyRole(userService.getRole(userId).getRole()).equals(2) && bookBorrowing.getBookCount() > 10)){
                return ResponseMessage.success(201, "借阅失败，您的借阅数量已达上限！", null);
            }
        }

        if (bookBorrowingService.countUserBorrowing(bookBorrowing.getUserId()) != null){
            if ((RoleVerify.verifyRole(userService.getRole(userId).getRole()).equals(1) && bookBorrowingService.countUserBorrowing(bookBorrowing.getUserId()) + bookBorrowing.getBookCount() > 5) || (RoleVerify.verifyRole(userService.getRole(userId).getRole()).equals(2) && bookBorrowingService.countUserBorrowing(bookBorrowing.getUserId()) + bookBorrowing.getBookCount() > 10)){
                return ResponseMessage.success(201, "借阅失败，您的借阅数量已达上限！", null);
            }
        }

        Integer stock = bookService.findStock(bookBorrowing.getBookId()); // 获取书籍库存

        if (stock == null) {
            return ResponseMessage.success(202, "借阅失败，书籍不存在或库存数据异常！", null);
        }
        if (bookService.getBookStatus(bookBorrowing.getBookId()).equals("UNDER_MAINTENANCE")){
            return ResponseMessage.success(203, "借阅失败，书籍正在维修中！", null);
        }

        if (stock >= bookBorrowing.getBookCount()){
            bookBorrowingService.borrowBook(bookBorrowing);
            bookService.stock(bookBorrowing.getBookId(),stock - bookBorrowing.getBookCount());
            if (stock == bookBorrowing.getBookCount()){ //如果借阅数量等于库存数量，更新书籍状态为借出
                bookService.updateBookStatus(bookBorrowing.getBookId(),"BORROWED"); //更新书籍状态为借出
            }
            return ResponseMessage.success(200, "借阅成功！", bookBorrowing);
        }else {
            return ResponseMessage.success(204, "借阅失败，书籍库存不足！", null);
        }
        }

        @PutMapping("/returnBook/{id}")
        @ApiOperation("还书")
        public ResponseMessage<BookBorrowing> returnBook(@RequestHeader("Authorization") String token, @PathVariable Integer id, @RequestBody BookBorrowing bookBorrowing) {
            Integer userId = VerifyLoginUtil.verifyLogin(token);
            if (userId == null || VerifyLoginUtil.isTokenValid(token)){
               return ResponseMessage.success(401, "Token无效或已过期", null);
            }
            if (bookBorrowing.getBorrowStatus().equals("逾期归还") || bookBorrowing.getBorrowStatus().equals("已归还")){
                return ResponseMessage.success(205,"还书失败，书籍已还！",bookBorrowing);
            }
            bookBorrowing.setId(id);
            Integer stock = bookService.findStock(bookBorrowing.getBookId()); // 获取书籍库存
            if (stock == null) {
                return ResponseMessage.success(206,"还书失败，书籍不存在或库存数据异常！", bookBorrowing);
            }
            if (bookBorrowingService.getReturnDate(id).isBefore(bookBorrowing.getRealReturnDate())){
                // 计算逾期天数和罚款
                long overDays = ChronoUnit.DAYS.between(bookBorrowingService.getReturnDate(id), bookBorrowing.getRealReturnDate());
                double fine = overDays * 1; // 假设每天罚款 1 元
                bookBorrowing.setBorrowStatus("逾期归还");
                bookBorrowing.setOverdueFine((int) fine);
                bookBorrowingService.returnBook(bookBorrowing);
                return ResponseMessage.success(200,"还书成功，您已逾期归还，请尽快处理！", bookBorrowing);
            }else {
                bookBorrowing.setBorrowStatus("已归还");
                bookBorrowingService.returnBook(bookBorrowing);
                bookService.stock(bookBorrowing.getBookId(),stock + bookBorrowing.getBookCount());
                if (bookService.getBookStatus(bookBorrowing.getBookId()) != "UNDER_MAINTENANCE"){
                    bookService.updateBookStatus(bookBorrowing.getBookId(),"AVAILABLE");
                }
                return ResponseMessage.success(200,"还书成功！", bookBorrowing);
            }
        }
}
